package com.onpositive.notes.parser;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.onpositive.notes.model.ITemplateModel;
import com.onpositive.notes.services.TemplateModelRegistry;

public class KeyWordParser implements Serializable {
	
	private static final long serialVersionUID = -8870489060872575242L;


	public KeyWordParser() {
		super();
	}


	static Set<String> templateKeys ;
	static Set<String> startingWords ;
	
	
	public static ArrayList<Block<TemplateOccurence>> detectKeyWords( String str ){
		
		if( str == null )
			return null ;
		
		ArrayList<Block<TemplateOccurence>> result = new ArrayList<Block<TemplateOccurence>>() ;
		init() ;
		ArrayList<Integer> wordBounds = markWords(str) ;
		for( int i = 0 ; i < wordBounds.size() ; i+=2 ){
			
			int start = wordBounds.get(i) ;
			int end = wordBounds.get(i+1) ;
			
			String word = str.substring(start, end).trim().toLowerCase() ;
			if(word.length() == 0)
				continue ;
				
			if( !startingWords.contains(word))
				continue ;
			
			List<String> actualKeys = TemplateModelRegistry.getInstance().getModelsByFirstWord(word.toLowerCase()) ;
			String str_lc = str.toLowerCase() ;
			
			for( String modelKey : actualKeys ){
				
				if(!str_lc.startsWith(modelKey, start))
					continue ;
			
				List<ITemplateModel<?>> models = TemplateModelRegistry.getInstance().getModelsByKey(modelKey);
				if( models == null || models.isEmpty() )
					continue ;
					
				ITemplateModel<?> model = models.iterator().next() ;
				TemplateOccurence to = new TemplateOccurence(model) ;
				
				Block<TemplateOccurence> blk =
						new Block<TemplateOccurence>(str, start, start+modelKey.length(), to, Block.BLOCK_KIND_KEYWORD) ;
				result.add( blk ) ;
				
				int spacesCount = modelKey.trim().replaceAll("[^\\s]", "").length() ;
				i += 2*spacesCount ;
				break ;
			}
			
		}		
		return result ;		
	}


	private static ArrayList<Integer> markWords(String str) {
		
		String[] separators = new String[]{ System.getProperty("line.separator"), "\r\n", "\n", "\r", "\t", " " } ;		
		ArrayList<Block<Mark>> split = SentenceSplitter.split(str, separators);
		ArrayList<Integer> result = new ArrayList<Integer>() ;
		result.add(0) ;
		for( Block<Mark> blk : split ){
			result.add( blk.getStart() ) ;
			result.add( blk.getEnd() ) ;
		}
		result.add(str.length()) ;		
		return result;
	}


	private static  void init() {		
		if( templateKeys == null )
			templateKeys = TemplateModelRegistry.getInstance().getAllTemplateKeys();
		if( startingWords == null )
			startingWords = TemplateModelRegistry.getInstance().getStartingWords();
		
	}
}
